# -*- coding: utf-8 -*-

import sys,os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ui_mainwindow import Ui_MainWindow
from ui_about import Ui_AboutWindow
from ui_openytlink import Ui_openYTLink
from ui_megavideo import Ui_megavideoDialog
from ui_preferences import Ui_Preferences
from ui_livelist import Ui_openLiveList

from downloader import *

class LiveShuffle(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)
		
		#used for downloading queue integrity 
		self.rows = []
		self.keys = 0
		self.slots = 5
		self.maxSlots = 5
		self.queue = []
		
		#setting up main window
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		#setting up timer for updating data table
		self.tableTimer = QTimer(self)
		
		#connects various ui events (new connection method used)
		self.ui.actionQuit.triggered.connect(self.quitApp)
		self.ui.actionAbout.triggered.connect(self.showAbout)
		self.ui.actionOpen_YouTube.triggered.connect(self.showOpenYTDialog)
		self.ui.actionMegaVideo.triggered.connect(self.showMegaVideoDialog)
		self.ui.actionPreferences.triggered.connect(self.showPreferencesDialog)
		self.ui.actionLiveList.triggered.connect(self.showLoadLLDialog)
		
		self.ui.searchButton.clicked.connect(self.getSong)
		self.ui.lineEdit.returnPressed.connect(self.getSong)
		self.tableTimer.timeout.connect(self.updateTable)
		
		#this call the refresh method every second
		self.tableTimer.start(1000) #t expressed in milliseconds
		
		#loads settings
		self.loadSettings()
	
	#using download slots for queueing
	def areThereSlots(self):
		if self.slots >=1:
			return True
	
	def getSlot(self):
		if self.areThereSlots() == True:
			self.slots -= 1
	
	def releaseSlot(self):
		self.slots += 1
	
	def loadSettings(self):
		#changing current working directory to script directory
		wdir = os.getcwd()
		os.chdir(os.path.abspath(os.path.dirname(__file__)))
		confFile = open("liveshuffle.conf", "r")
		for line in confFile:
			chunks = line.split("=")
			rule = chunks[0]
			value = chunks[1].rstrip("\n")
			setattr(self,rule,value)
	
	#used to see if some methods really works - just for debugging
	def ping(self):
		print "ping!"
	
	#show livelist loading dialog
	def showLoadLLDialog(self):
		#openlivelist object
		oll = QDialog()
		uiOll = Ui_openLiveList()
		self.uiOll = uiOll #just for having it quite global
		uiOll.setupUi(oll)
		
		#connecting dialog events
		uiOll.okButton.clicked.connect(oll.accept)
		uiOll.cancelButton.clicked.connect(oll.reject)
		
		uiOll.selectFileButton.clicked.connect(self.liveListLoad)
		
		oll.setModal(True)
		oll.show()
		if oll.exec_() == 1:
			livelist = uiOll.linkEdit.text().__str__()
			llFile = open(livelist, "r")
			
			i = 0
			for line in llFile:
				if i<1:
					chunks = line.split("|")
					tAuthor = chunks[0].rstrip("\n")
					tAlbum = chunks[1].rstrip("\n")
				if i>1:
					if len(line) != 0:
						chunks = line.split("|")
						tTrack = chunks[0].rstrip("\n")
						tTitle = chunks[1].rstrip("\n")
						tLink = chunks[2].rstrip("\n")
						#opening new download
						new = self.getSongFromLink(tLink)
						new.setAlbum(tAlbum)
						new.setAuthor(tAuthor)
						new.setTrack(tTrack)
						new.setTitle(tTitle)
						new.enableTags()
				i += 1
	
	def liveListLoad(self):
		fd = QFileDialog()
		file = fd.getOpenFileNameAndFilter(self, 'Select LiveList','/home',"LiveList (*.ll)")
		rfile = file[0].__str__()
		self.uiOll.linkEdit.setText(rfile)
	
	#open preferences dialog
	def showPreferencesDialog(self):
		self.p = QDialog()
		self.p.setModal(True)
		self.pUi = Ui_Preferences()
		self.pUi.setupUi(self.p)
		
		#connecting events
		self.pUi.cancelButton.clicked.connect(self.p.reject)
		self.pUi.saveButton.clicked.connect(self.p.accept)
		
		#loading data
		# - song format
		if self.AudioFormat == "mp3":
			self.pUi.mp3Button.setChecked(True)
			self.pUi.oggButton.setChecked(False)
		else:
			self.pUi.oggButton.setChecked(True)
			self.pUi.mp3Button.setChecked(False)
		# - mantaining video
		if self.MantainAudioVideo == "yes":
			self.pUi.maintainVideoBox.setChecked(True)
		else:
			self.pUi.maintainVideoBox.setChecked(False)
		# - audio folder
		self.pUi.audioFolderEdit.setText(self.AudioFolder)
		# - video folder
		self.pUi.videoFolderEdit.setText(self.VideoFolder)
		
		self.p.setModal(True)
		self.p.show()
		
		self.pUi.selectAudioButton.clicked.connect(self.setPrepAudio)
		self.pUi.selectVideoButton.clicked.connect(self.setPrepVideo)
		
		#if modal is accepted, save settings
		if self.p.exec_() == 1:
			#setting options in realtime
			# - song format
			if self.pUi.mp3Button.isChecked() == True:
				self.AudioFormat = "mp3"
			else:
				self.AudioFormat = "ogg"
			# - mantain video
			if self.pUi.maintainVideoBox.isChecked() == True:
				self.MantainAudioVideo = "yes"
			else:
				self.MantainAudioVideo = "no"
			# - audio folder
			if self.pUi.audioFolderEdit.text().__str__()[-1] == "/":
				self.AudioFolder = self.pUi.audioFolderEdit.text().__str__()
			else:
				self.AudioFolder = self.pUi.audioFolderEdit.text().__str__()+"/"
			# - video folder
			if self.pUi.videoFolderEdit.text().__str__()[-1] == "/":
				self.VideoFolder = self.pUi.videoFolderEdit.text().__str__()
			else:
				self.VideoFolder = self.pUi.videoFolderEdit.text().__str__()+"/"
			
			#writing new conf file
			os.remove("liveshuffle.conf")
			out_file = open("liveshuffle.conf","w")
			out_file.write("AudioFormat="+self.AudioFormat+"\n")
			out_file.write("AudioFolder="+self.AudioFolder+"\n")
			out_file.write("MantainAudioVideo="+self.MantainAudioVideo+"\n")
			out_file.write("VideoFolder="+self.VideoFolder+"\n")
			out_file.close()
	
	def setPrepAudio(self):
		fs = QFileDialog()
		fs.setFileMode(QFileDialog.Directory)
		folder = fs.getExistingDirectory(self, 'Select Audio Folder','/home')
		self.pUi.audioFolderEdit.setText(folder)
	
	def setPrepVideo(self):
		fs = QFileDialog()
		fs.setFileMode(QFileDialog.Directory)
		folder = fs.getExistingDirectory(self, 'Select Video Folder','/home')
		self.pUi.videoFolderEdit.setText(folder)
	
	#open megavideo dialog
	def showMegaVideoDialog(self):
		mv = QDialog()
		mvUi = Ui_megavideoDialog()
		mvUi.setupUi(mv)
		mv.setModal(True)
		mv.show()
		mv.exec_()
		link = mvUi.link.text().__str__()
		title = mvUi.title.text().__str__()
		#if link is valid (not empty) request the downloader for a new download
		if link and title:
			self.getMovie(link,title)
	
	#open youtube dialog
	def showOpenYTDialog(self):
		openytlink = QDialog()
		uiopenytlink = Ui_openYTLink()
		uiopenytlink.setupUi(openytlink)
		openytlink.setModal(True)
		openytlink.show()
		openytlink.exec_()
		link = uiopenytlink.linkEdit.text()
		#if link is valid (not empty) request the downloader for a new download
		if link:
			self.getSongFromLink(link.__str__())
		
	#refresh processes status in the table
	# unique for all services
	def updateTable(self):
		for song in self.rows[:]:
			#extract array data
			key = song[0]
			process = song[1]
			
			process.update() #update step by step is necessary due to fake parallelism
			
			status = process.GetStatus() #get status of every process
			
			#update the shown status on table
			if status == 0:
				self.ui.tableWidget.setItem(key,0,QTableWidgetItem("completed"))
				self.rows.remove([key,process])
			elif status == 1:
				self.ui.tableWidget.setItem(key,0,QTableWidgetItem("encoding"))
			elif status == 2:
				self.ui.tableWidget.setItem(key,0,QTableWidgetItem("downloading"))
			elif status == 3:
				self.ui.tableWidget.setItem(key,0,QTableWidgetItem("preparing"))
	
	#used to add a megavideo link in queue
	def getMovie(self,link,title):
		self.ui.lineEdit.clear()
		#create download object
		p = GetMovieProcess(link,title,self)
		#set metadata
		movieTitle = QTableWidgetItem(title)
		movieCat = QTableWidgetItem("Movie\TV Series")
		movieStatus = QTableWidgetItem("waiting")
		#insert metadata into table
		self.ui.tableWidget.insertRow(self.keys)
		self.ui.tableWidget.setItem(self.keys,0,movieStatus)
		self.ui.tableWidget.setItem(self.keys,1,movieCat)
		self.ui.tableWidget.setItem(self.keys,2,movieTitle)
		#add download to queue
		p.getMegaVideo()
		self.rows.append([self.keys, p])
		self.keys += 1
	
	#used when searching directly from searchbox
	def getSong(self):
		mySong = self.ui.lineEdit.text()
		self.ui.lineEdit.clear()
		#create new download object
		p = GetSongProcess(self)
		#get some metadata
		info = p.GetFirstEntryDetails(mySong.__str__())
		songTitle = QTableWidgetItem(info[0])
		songCat = QTableWidgetItem(info[1])
		songStatus = QTableWidgetItem("waiting")
		#insert metadata into table
		self.ui.tableWidget.insertRow(self.keys)
		self.ui.tableWidget.setItem(self.keys,0,songStatus)
		self.ui.tableWidget.setItem(self.keys,1,songCat)
		self.ui.tableWidget.setItem(self.keys,2,songTitle)
		#add song to download queue
		p.GetSong(mySong)
		self.rows.append([self.keys, p])
		self.keys += 1
	
	#used when inserting a direct youtube link
	def getSongFromLink(self,link):
		self.ui.lineEdit.clear()
		p = GetSongProcess(self)
		info = p.GetFirstEntryDetails(link)
		
		songTitle = QTableWidgetItem(info[0])
		songCat = QTableWidgetItem(info[1])
		songStatus = QTableWidgetItem("waiting")
		
		
		self.ui.tableWidget.insertRow(self.keys)
		self.ui.tableWidget.setItem(self.keys,0,songStatus)
		self.ui.tableWidget.setItem(self.keys,1,songCat)
		self.ui.tableWidget.setItem(self.keys,2,songTitle)
		
		p.GetSongFromLink(link)
		self.rows.append([self.keys, p])
		self.keys += 1
		return p
	
	#shows about box
	def showAbout(self):
		aboutWindow = QDialog()
		uiAbout = Ui_AboutWindow()
		uiAbout.setupUi(aboutWindow)
		aboutWindow.setModal(True)
		aboutWindow.show()
		aboutWindow.exec_()
	
	#quit application
	def quitApp(self):
		sys.exit()

app = QApplication(sys.argv)
lf = LiveShuffle()
lf.show()
sys.exit(app.exec_())
